package com.wsoft.core.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import com.sun.mail.util.MailSSLSocketFactory;
import com.wsoft.core.service.CommonConfigService;
import com.wsoft.core.vo.ConfigQuery;
import com.wsoft.enums.TemplateTypeEnum;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.security.GeneralSecurityException;
import java.util.Map;

/**
 * @Author Zhang gukai
 * @Date 2024/11/27 10:26
 */
@Component
public class EmailUtil {
    @Resource
    private CommonConfigService commonConfigService;

    public void sendEmail(String to, String subject, String content, String type) {
        ConfigQuery query = new ConfigQuery();
        query.setCode("email");
        Map<String, String> map = commonConfigService.getConfigValue(query);
        //配置
        MailAccount account = new MailAccount();
        account.setHost(map.get("host"));
        account.setPort(Integer.parseInt(map.get("port")));
        account.setAuth(Boolean.parseBoolean(map.get("auth")));
        account.setFrom(map.get("from"));
        account.setUser(map.get("user"));
        account.setPass(map.get("pass"));
        account.setSslEnable(Boolean.parseBoolean(map.get("auth")));
        // 发送
        try {
            MailSSLSocketFactory sf = null;
            try {
                sf = new MailSSLSocketFactory();
            } catch (GeneralSecurityException e) {
                throw new RuntimeException(e);
            }
             sf.setTrustAllHosts(true);
//            sf.setTrustedHosts(new String[]{"smtp.qq.com"});
            account.setCustomProperty("mail.smtp.ssl.socketFactory", sf);
            if (TemplateTypeEnum.HTML.getCode().equals(type)){
                MailUtil.send(account, CollUtil.newArrayList(to), subject, content, true);
            }
            else {
                MailUtil.send(account, CollUtil.newArrayList(to), subject, content, false);
            }

        }catch (Exception e){
            System.out.println(e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }

}
